package main

import "fmt"

/*
从上往下打印出二叉树的每个节点，同层节点从左至右打印。
思路：头结点压入队列，读出头结点的时候将头节点的左右子节点压入队列，依次循环，直到将队列中所有值读出
*/

type TreeNode struct {
	val       int
	leftNode  *TreeNode
	rightNode *TreeNode
}

func main() {
	root := TreeNode{val: 8}
	root.leftNode = &TreeNode{val: 3}
	root.rightNode = &TreeNode{val: 10}
	root.leftNode.leftNode = &TreeNode{val: 1}
	root.leftNode.rightNode = &TreeNode{val: 6}
	root.leftNode.rightNode.leftNode = &TreeNode{val: 4}
	root.leftNode.rightNode.rightNode = &TreeNode{val: 7}
	root.rightNode.rightNode = &TreeNode{val: 14}
	root.rightNode.rightNode.leftNode = &TreeNode{val: 13}

	fmt.Println(PrintFormTopToBottom(&root))
}

func PrintFormTopToBottom(root *TreeNode) []int {
	if root == nil {
		return nil
	}
	var queue []*TreeNode
	var layerList []int

	queue = append(queue, root)
	for len(queue) != 0 {
		node := queue[0]
		layerList = append(layerList, node.val)
		queue = queue[1:]
		if node.leftNode != nil {
			queue = append(queue, node.leftNode)
		}
		if node.rightNode != nil {
			queue = append(queue, node.rightNode)
		}
	}

	return layerList
}
